package com.learn.concurrent.itcast.thread.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadAndWriteLockTest4 {

    public static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public static void main(String[] args) {
        //同时写
        ExecutorService executorService= Executors.newCachedThreadPool();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                writeFile(Thread.currentThread());
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                writeFile(Thread.currentThread());
            }
        });
    }

    //读操作
    public static void readFile(Thread thread){
        lock.readLock().lock();
        boolean readLock=lock.isWriteLocked();
        if(!readLock){
            System.out.println("当前为读锁");
        }
        System.out.println("start time:"+System.currentTimeMillis());
        try{
            for (int i = 0; i < 6; i++) {
                try {
                    Thread.sleep(200);
                    System.out.println(thread.getName()+"正在进行读操作");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(thread.getName()+"读操作完毕");
            System.out.println("end time"+System.currentTimeMillis());
        }finally {
            System.out.println("释放读锁！");
            lock.readLock().unlock();
        }
    }

    //写操作
    public static void writeFile(Thread thread){

        lock.writeLock().lock();
        boolean readLock=lock.isWriteLocked();
        if(readLock){
            System.out.println("当前为写锁");
        }
        System.out.println("start time:"+System.currentTimeMillis());
        try{
            for (int i = 0; i < 6; i++) {
                try {
                    Thread.sleep(200);
                    System.out.println(thread.getName()+"正在进行写操作");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(thread.getName()+"写操作完毕");
            System.out.println("end time"+System.currentTimeMillis());
        }finally {
            System.out.println("释放写锁！");
            lock.writeLock().unlock();
        }

    }
}
